//
//  SlideTableViewController.m
//  ksjv2
//
//  Created by mac on 14/12/19.
//  Copyright (c) 2014年 CnbizMedia. All rights reserved.
//

#import "SlideTableViewController.h"
//#import "UIViewController+MMDrawerController.h"
#import "Util.h"
#import "DPMeterView.h"
#import "UIBezierPath+BasicShapes.h"
#import "TableViewController.h"
#import "MainTabBarController.h"
#import "LoginViewController.h"
//---------------------------------------------------------
//                    *              *
//                  *      首页侧边     *
//                    *              *
//---------------------------------------------------------
@interface SlideTableViewController ()<UITableViewDataSource,UITableViewDelegate,EGORefreshTableHeaderDelegate>{
    NSMutableDictionary*AllDict;//列表所以数据
    
    NSMutableArray*Selected;//已选中数组
    NSMutableArray*UnSelected;//未选数组
    
    NSMutableArray*Columns;//已选---栏目
    NSMutableArray*UnColumns;//未选栏目
    
    NSMutableArray*Author;//已选---专栏
    NSMutableArray*UnAuthor;//未选----专栏

    NSMutableArray*AddArray;//添加数组
    NSMutableArray*DelArray;//删除数组
    BOOL isLongin;

}
@property(nonatomic,strong)EGORefreshTableHeaderView * refreshHeaderView;
@property(nonatomic,assign)BOOL reloading;
@property (weak,nonatomic)IBOutlet UITableView*tableView;
@property (weak, nonatomic) IBOutlet UIButton *Done;
@property (strong, nonatomic) UISegmentedControl *SegmentedC;

@end

@implementation SlideTableViewController
@synthesize refreshHeaderView=_refreshHeaderView;
@synthesize reloading=_reloading;
- (void)viewDidLoad {
    [super viewDidLoad];
    [SVProgressHUD show];
    [self initData];
    [self initSegmented];
    isLongin=IFUserLogin?YES:NO;
}
-(void)initSegmented{

    self.SegmentedC=[[UISegmentedControl alloc]initWithItems:@[@"栏目",@"专栏"]];
    self.SegmentedC.frame=CGRectMake(-3, 65, self.view.frame.size.width*0.6+6, 29);
    self.SegmentedC.selectedSegmentIndex=0;
    self.SegmentedC.tintColor=[UIColor colorWithWhite:0.702 alpha:1.000];
    self.SegmentedC.backgroundColor=[UIColor whiteColor];
    [self.SegmentedC addTarget:self action:@selector(Segmented:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.SegmentedC];
}
-(void)initData{
    self.tableView.tableFooterView=[[UIView alloc]initWithFrame:CGRectZero];
    EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0,self.tableView.frame.origin.y-85, self.view.frame.size.width*0.6+45, 0)];
    view.delegate = self;
    [self.tableView addSubview:view];
    self.refreshHeaderView = view;
    [self.Done setEnabled:NO];
    AllDict=[[NSMutableDictionary alloc]init];
    
    Columns=[[NSMutableArray alloc]init];
    UnColumns=[[NSMutableArray alloc]init];
    AddArray=[[NSMutableArray alloc]init];
    DelArray=[[NSMutableArray alloc]init];
    Author=[[NSMutableArray alloc]init];
    UnAuthor=[[NSMutableArray alloc]init];
    Selected=Columns;
    UnSelected=UnColumns;
    [AllDict setObject:Selected forKey:@"0"];
    
    self.Done.tag=1;
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)viewWillAppear:(BOOL)animated{
    BOOL isl=IFUserLogin?YES:NO;
    if(isl==isLongin){
        if (Columns.count==0 && UnColumns.count==0) {
            [self loadNews];
        }
    }else{
    [UnColumns removeAllObjects];
//    [UnAuthor removeAllObjects];
    [Columns removeAllObjects];
//    [Author removeAllObjects];
    [self loadNews];
    }
    
}
-(void)loadNews{
    ///栏目
    
    [self.Done setEnabled:NO];
    [[AppAPIClient sharedClient] GET:@"Category/Subscribe" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        if (![responseObject[@"data"] isKindOfClass:[NSArray class]]){
            return ;
        }
        [self loadUnColumnsData];
        for (NSDictionary*dic in responseObject[@"data"]) {
            [Columns addObject:dic];
        }
        if (Columns.count==0) {
            Columns=[NSMutableArray arrayWithArray:responseObject[@"data"]];
        }
        [self.tableView reloadData];
        [self.refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"ERR: %@",operation.responseString);

    }];
//    专栏
    [[AppAPIClient sharedClient] GET:@"Column/List" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [Author removeAllObjects];
        [UnAuthor removeAllObjects];
//        for (NSDictionary*dic in responseObject[@"data"]) {
//            [Author addObject:dic];
//        }
//        if (Author.count==0) {
//            Author=[NSMutableArray arrayWithArray:responseObject[@"data"]];
//        }
        if (IFUserLogin) {
            
        
        for (NSString*str in responseObject[@"data"]) {
            NSString*str_i=[str  componentsSeparatedByString:@"|"][2];
            if ([str_i isEqualToString:@"1"]) {
                [Author addObject:[str  componentsSeparatedByString:@"|"][1]];

            }else{
                [UnAuthor addObject:[str  componentsSeparatedByString:@"|"][1]];
            }
            
        }
        }else{
            for (NSString*str in responseObject[@"data"]) {
//                NSString*str_i=[str  componentsSeparatedByString:@"|"][2];

                [Author addObject:[str  componentsSeparatedByString:@"|"][1]];

            }
        }
        [self.tableView reloadData];
        [self.refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"ERR: %@",operation.responseString);
        
    }];
    
}
-(void)loadUnColumnsData{
    [[AppAPIClient sharedClient] GET:@"Category/Index" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSMutableDictionary *result = responseObject[@"data"];
            if([result isKindOfClass:[NSNull class]] || [result count] == 0){
                return;
            }
            [UnColumns addObjectsFromArray:responseObject[@"data"]];
        for (NSDictionary*dic in Columns) {
            for (NSDictionary*_dic in UnColumns) {
                if ([dic[@"catname"] isEqualToString:_dic[@"catname"]]) {
                    [UnColumns removeObject:_dic];
                    break;
                }
            }
            
        }
        [SVProgressHUD dismiss];
        [self.Done setEnabled:YES];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"ERR: %@",operation.responseString);
            
        }];
}

-(void)AddOfDel{
    
    if(AddArray.count!=0){
        NSMutableArray*arrat=[[NSMutableArray alloc]init];
        
        if (self.SegmentedC.selectedSegmentIndex==1) {
            NSString* string=[[NSString alloc]init]; // 结果字符串

            for (NSString*dic in Selected) {
                string = [string stringByAppendingFormat:@",%@", dic];

            }
            

            NSString *trimmedString = [string substringFromIndex:1];
            [[AppAPIClient sharedClient] POST:@"Column/Update" parameters:@{@"data":trimmedString} success:^(AFHTTPRequestOperation *operation, id responseObject) {
                
                [AddArray removeAllObjects];
                [self.tableView reloadData];
                
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"ERR: %@",operation.responseString);
                
            }];
        }else{
            for (NSDictionary*dic in Selected) {
                [arrat addObject:dic[@"catid"]];
            }

            NSString* string=[[NSString alloc]init]; // 结果字符串
            
            for (NSString*dic in arrat) {
                string = [string stringByAppendingFormat:@",%@", dic];
                
            }

            [[AppAPIClient sharedClient] GET:@"Category/Subscribe" parameters:@{@"catid": [string substringFromIndex:1]} success:^(AFHTTPRequestOperation *operation, id responseObject) {
                
                [AddArray removeAllObjects];
                [self.tableView reloadData];
                
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"ERR: %@",operation.responseString);
                
            }];
        }
        
        
    
    }else if (DelArray.count!=0){

        NSMutableArray*arrat=[[NSMutableArray alloc]init];
    if (Selected==Author) {
            arrat=Selected;
            NSString* string=[[NSString alloc]init]; // 结果字符串
            
            for (NSString*dic in arrat) {
                string = [string stringByAppendingFormat:@",%@", dic];
                
            }

            NSString *trimmedString = [string substringFromIndex:1];
        [[AppAPIClient sharedClient] POST:@"Column/Update" parameters:@{@"data":trimmedString} success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            [DelArray removeAllObjects];
            [self.tableView reloadData];
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"ERR: %@",operation.responseString);
            
        }];
    }else{
        for (NSDictionary*dic in Selected) {
            [arrat addObject:dic[@"catid"]];
        }
            NSString* string=[[NSString alloc]init]; // 结果字符串
            
            for (NSString*dic in arrat) {
                string = [string stringByAppendingFormat:@",%@", dic];
                
            }
            
            
            NSString *trimmedString = [string substringFromIndex:1];
        [[AppAPIClient sharedClient] GET:@"Category/Subscribe" parameters:@{@"catid":trimmedString} success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            [DelArray removeAllObjects];
            [self.tableView reloadData];
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"ERR: %@",operation.responseString);
            
        }];
    }

    }
    
}
- (void)Segmented:(id)sender {
    UISegmentedControl*seg=(UISegmentedControl*)sender;
    if (seg.selectedSegmentIndex) {
        
        Selected=Author;
        
        UnSelected=UnAuthor;
        
        
    }else{
//        [AllDict setObject:Author forKey:@"0"];
        Selected=Columns;
        [UnSelected removeAllObjects];
        UnSelected=UnColumns;
    }
    [AllDict setObject:Selected forKey:@"0"];
    [self.Done setImage:nil forState:UIControlStateNormal];
    self.Done.tag=1;
    [AllDict removeObjectForKey:@"1"];
    [self.tableView reloadData];
}

- (IBAction)DoneAction:(id)sender {
    if (IFUserLogin) {

    if (self.Done.tag==1) {
        [self.Done setImage:[UIImage imageNamed:@"gou"] forState:UIControlStateNormal];
        [AllDict setObject:UnSelected forKey:@"1"];
        self.Done.tag=0;
    }else{
        [self.Done setImage:nil forState:UIControlStateNormal];
        [AllDict removeObjectForKey:@"1"];
        self.Done.tag=1;
        [self AddOfDel];

    }
    [self.tableView reloadData];
    
    }else{
        UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
        LoginViewController*login=[story instantiateViewControllerWithIdentifier:@"LoginViewController"];
        UINavigationController*nav=[[UINavigationController alloc]initWithRootViewController:login];

        [self presentViewController:nav animated:YES completion:nil];
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return [[AllDict allKeys] count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [[AllDict objectForKey:[NSString stringWithFormat:@"%d",section]] count];
}
//-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return 55;
//}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 55;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView*view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 10)];
    view.backgroundColor=UIColorFromRGB(0xf5f5f5);
    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell;
    NSDictionary*dic;
    if (indexPath.section==0) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"slide1" forIndexPath:indexPath];
        if (cell==nil) {
            cell = [tableView dequeueReusableCellWithIdentifier:@"slide1"];
        }
        dic=Selected[indexPath.row];
    }else{
        cell = [tableView dequeueReusableCellWithIdentifier:@"slide2" forIndexPath:indexPath];
        if (cell==nil) {
            cell = [tableView dequeueReusableCellWithIdentifier:@"slide2"];
        }
        
        dic=UnSelected[indexPath.row];
    }
    UIButton*button=(UIButton*)[cell.contentView viewWithTag:55];

    if (self.Done.tag==0) {
        button.hidden=NO;
    }else{
        button.hidden=YES;
    }
    if([[dic class] isSubclassOfClass:[NSString class]]){
        UILabel*name=(UILabel*)[cell.contentView viewWithTag:22];
        name.text=[NSString stringWithFormat:@"%@",dic];
    }else if ([dic allKeys].count>1) {
    UIImageView*image=(UIImageView*)[cell.contentView viewWithTag:11];
    [image sd_setImageWithURL:[NSURL URLWithString:dic[@"image"]]];
    UILabel*name=(UILabel*)[cell.contentView viewWithTag:22];
    name.text=dic[@"catname"];
    }
        
    
    
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.Done.tag==0) {
        
        if (indexPath.section==0) {
            if (self.SegmentedC.selectedSegmentIndex==1) {
                [DelArray addObject:Selected[indexPath.row]];
            }else{
            [DelArray addObject:Selected[indexPath.row]];
            }
        [UnSelected addObject:Selected[indexPath.row]];
        [Selected removeObjectAtIndex:indexPath.row];
        [self.tableView reloadData];
        
        }else{
            if (self.SegmentedC.selectedSegmentIndex==1) {
                [AddArray addObject:UnSelected[indexPath.row]];
            }else{
            [AddArray addObject:UnSelected[indexPath.row][@"catid"] ];
            }
        [Selected addObject:UnSelected[indexPath.row]];
        [UnSelected removeObjectAtIndex:indexPath.row];
        [self.tableView reloadData];
        
        }
        
    }else{
        
        if (self.SegmentedC.selectedSegmentIndex==0) {
            self.mainVC.PscrollHidden=@"0";
            self.mainVC.slug=Columns[indexPath.row][@"catdir"];
            [self.mainVC setTitle:Columns[indexPath.row][@"catname"] ];
//            [self.mm_drawerController toggleDrawerSide:MMDrawerSideRight animated:YES completion:nil];
        }else{
            self.mainVC.PscrollHidden=@"1";
//            NSArray *arr = [Author[indexPath.row] componentsSeparatedByString:@"|"];
            self.mainVC.slug=Author[indexPath.row];
            [self.mainVC setTitle:Author[indexPath.row] ];
//            [self.mm_drawerController toggleDrawerSide:MMDrawerSideRight animated:YES completion:nil];
        }
        
    }

}
#pragma mark - UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    self.reloading = NO;
    [self.refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    [self.refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    
}
#pragma mark RefreshHeaderViewDelegate Methods

-(void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView *)view{
    self.reloading=YES;
    [self performSelector:@selector(doneLoadingViewData) withObject:nil afterDelay:2.0];
}
- (void)doneLoadingViewData{
    
    //  model should call this when its done loading
    self.reloading = NO;

    [Columns removeAllObjects];
    [self loadNews];
    
}
-(BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView *)view{
    return self.reloading;
}
-(NSDate *)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView *)view{
    return [NSDate date];
}

#pragma mark - Button Handlers
//-(void)leftDrawerButtonPress:(id)sender{
//    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
//}

-(void)rightDrawerButtonPress:(id)sender{
//    [self.mm_drawerController toggleDrawerSide:MMDrawerSideRight animated:YES completion:nil];
}

//-(void)doubleTap:(UITapGestureRecognizer*)gesture{
//    [self.mm_drawerController bouncePreviewForDrawerSide:MMDrawerSideLeft completion:nil];
//}

-(void)twoFingerDoubleTap:(UITapGestureRecognizer*)gesture{
//    [self.mm_drawerController bouncePreviewForDrawerSide:MMDrawerSideRight completion:nil];
}


@end
